package com.xyhuo.leetcode.january;

import java.util.HashMap;
import java.util.Map;

/**
 * 最大字符串配对数目
 * https://leetcode.cn/problems/find-maximum-number-of-string-pairs
 *
 * @time 2024/1/17
 */
public class MaximumNumberOfStringPairs {

    public int maximumNumberOfStringPairs(String[] words) {
        Map<String, Integer> wordMap = new HashMap<>();
        for (int i = 0; i < words.length; i++) {
            wordMap.put(words[i], i);
        }
        int ans = 0;
        int[] already = new int[words.length];
        for (int i = 0; i < words.length; i++) {
            String reverseWord = reverseStr(words[i]);
            if (reverseWord.equals(words[i])) {
                continue;
            }
            if (wordMap.containsKey(reverseWord)) {
                Integer index = wordMap.get(reverseWord);
                if (already[index] == 1) {
                    continue;
                }
                already[index] = 1;
                already[i] = 1;
                ans++;
            }
        }
        return ans;
    }

    private String reverseStr(String word) {
        StringBuilder sb = new StringBuilder();
        char[] charArray = word.toCharArray();
        for (int i = charArray.length - 1; i >= 0; i--) {
            sb.append(charArray[i]);
        }
        return sb.toString();
    }
}
